package com.lf.socket;

import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/webSocket")
public class WebSocketDemo {

	private static CopyOnWriteArraySet<WebSocketDemo> webSocketSet = new CopyOnWriteArraySet<>();
	private Session session;
	@OnOpen
	public void onOpen(Session session){
		this.session = session;
		webSocketSet.add(this);
	}
	@OnClose
	public void onClose(){
		System.out.println("onClose");
	}
	@OnMessage
	public void onMessage(String message,Session session){
		broadcast(String.format("%s", message));
	}
	private void broadcast(String info){
		for(WebSocketDemo w:webSocketSet){
			try {
				synchronized(WebSocketDemo.class){
					/*StringBuffer sb = new StringBuffer();
					String[] message = info.split(" ");*/
					/*for (int i = 0; i < message.length; i++) {
						String[] cid = message[i].split("-");
						sb.append("<a href='showContent?cid="+cid[0]+"'>"+cid[1]+"</a>"+"<br>");
					}*/
					w.session.getBasicRemote().sendText(info);
				}
			} catch (Exception e) {
				webSocketSet.remove(w);
				try {
					w.session.close();
				} catch (Exception e2) {
				}
			}
		}
	}
}
